package com.ivr.cm;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.core.task.TaskExecutor;

import com.hisunsray.intersp.TCPSpServer;
import com.hisunsray.vspp.data.PacketHeadVO;
import com.hisunsray.vspp.data.PacketInfoVO;
/**
 * 客户端链接高阳网关服务
 * @author liugeng
 * @date 2015-12-15
 * @version 1.0
 */
public class VsppClient implements Runnable {
	private static Logger logger = Logger.getLogger(VsppClient.class);
	
	private static TCPSpServer tcpServer = null;//SP TCP服务类
	private int port;	//端口号
	private int key;	//参数key
	public TaskExecutor taskExecutor;	//定义线程
	
	public TaskExecutor getTaskExecutor() {
		return taskExecutor;
	}
	public void setTaskExecutor(TaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}
	
	public VsppClient(int port,int key) throws Exception{
		this.port = port;
		this.key = key;
		
		//没有做多线程同步
		if(tcpServer != null){
			return;
		}
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		tcpServer = new TCPSpServer();
		/**初始化调用高阳网管开始*/
		logger.info("南京美游调用VSPP高阳网关初始化开始");
		
		int result = 0;
		try{
			logger.info(String.format("VsppClient vsppCommInit(%d,%d)", port, key));
			result = tcpServer.vsppCommInit(port, key);
		}catch (Exception e) {
			logger.error(String.format("调用VSPP高阳网关初始化失败:%s", ExceptionUtils.getFullStackTrace(e)));
			/**结束进程*/
			System.exit(1);
		}
		logger.info(String.format("调用VSPP高阳网关初始化返回结果：%d", result));
		
		/**调用网关正常开始循环接收数据*/
		while(true){
			/**定义高阳包体内容VO*/
			PacketInfoVO packetInfo = null;
			try{
				/**接收高阳网关对象*/
				packetInfo = tcpServer.vsppReceiveMessage();
			}catch (Exception e) {
				logger.error(String.format("网关接收消息异常:%s", ExceptionUtils.getFullStackTrace(e)));
				packetInfo = null;
			}
			
			/**判断包体是否为空*/
			if(packetInfo == null){
				continue;
			}
			
			/**包体内容记录日志信息*/
			PacketHeadVO packetHead = packetInfo.getPaHeadVO();
			logger.info(String.format("[%s][%s]接收到请求：seqNO=%s,serverid=%s,operateid=%s,body=%s",
					packetHead.getCallingNUMBER(),packetHead.getCalledNUMBER(), 
					packetInfo.getPaHeadVO().getSeqNo(), packetHead.getServerID(), packetHead.getOperateID(),
					packetInfo.getPacketBody()));
			
			/**用线程池处理业务逻辑*/
			HandleThread thread = new HandleThread(packetInfo, tcpServer);
			taskExecutor.execute(thread);
		}
	}
}
